package com.userdemo.demo.service.base.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.userdemo.demo.annotation.SysLog;
import com.userdemo.demo.base.BaseService;
import com.userdemo.demo.common.sys.ServerResponse;
import com.userdemo.demo.constant.base.Const;
import com.userdemo.demo.dao.base.BaseRoleMechanismMapper;
import com.userdemo.demo.entity.base.BaseRole;
import com.userdemo.demo.entity.base.dto.BaseRoleDTO;
import com.userdemo.demo.entity.base.vo.BaseRoleVO;
import com.userdemo.demo.entity.base.vo.BaseUserVO;
import com.userdemo.demo.service.base.IBaseRoleService;
import com.userdemo.demo.util.base.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 　　* @description: 角色服务层
 * 　　* @param ${tags}
 * 　　* @return ${return_type}
 * 　　* @throws
 * 　　* @author 陈宇
 * 　　* @date $date$ $time$
 *
 */
@Service("iBaseRoleService")
@Transactional
public class BaseRoleServiceImpl extends BaseService implements IBaseRoleService {
    Logger logger = LoggerFactory.getLogger(BaseRoleServiceImpl.class);
    @Resource
    private BaseRoleMechanismMapper baseRoleMechanismMapper;

    /**
     * 新增/更新角色信息
     *
     * @param baseRoleDTO
     * @param baseUserVO
     * @return
     */
    @SysLog("新增/更新角色信息")
    @Override
    public ServerResponse<String> addOrUpdateRole(BaseRoleDTO baseRoleDTO, BaseUserVO baseUserVO) {
        if(null == baseRoleDTO || null == baseUserVO) {
            return ServerResponse.createByErrorMessage("参数错误");
        }
        BaseRole baseRole = new BaseRole();
        Date now  = new Date();
        if(null != baseRoleDTO.getRoleId() && 0 < baseRoleDTO.getRoleId()){
            baseRole = baseRoleMapper.selectByPrimaryKey(baseRoleDTO.getRoleId());

            baseRole.setRoleName(baseRoleDTO.getRoleName());
            baseRole.setRoleDescInfo(baseRoleDTO.getRoleDescInfo());
            baseRole.setCompanyId(baseUserVO.getCompanyId());
            baseRole.setUseType(baseUserVO.getUseType());
            baseRole.setUpdateUser(baseUserVO.getUserName());
            baseRole.setIsPublish(1);

            if(baseRoleMapper.updateByPrimaryKeySelective(baseRole) > 0){
                return ServerResponse.createBySuccessMessage("更新成功");
            }

        }else
        {

                baseRole.setId(baseRoleMapper.selectSeq());
                baseRole.setRoleName(baseRoleDTO.getRoleName());
                baseRole.setRoleDescInfo(baseRoleDTO.getRoleDescInfo());
                baseRole.setCompanyId(baseUserVO.getCompanyId());
                baseRole.setIsPublish(1);
                baseRole.setUseType(baseUserVO.getUseType());
                baseRole.setCreateOrgId(baseUserVO.getCreateOrgId());
                baseRole.setCreateTopId(baseUserVO.getCreateTopOrgId());
                baseRole.setCreateUser(baseUserVO.getUserName());
                baseRole.setUpdateUser(baseUserVO.getUserName());
                baseRole.setUpdateTime(now);
                baseRole.setCreateTime(now);

                if(baseRoleMapper.insertSelective(baseRole) > 0){
                    return ServerResponse.createBySuccessMessage("新增成功");
                }
        }

        return ServerResponse.createByErrorMessage("操作失败");
    }

    /**
     * ID删除用户角色
     *
     * @param baseRoleDTO
     * @return
     */
    @SysLog("ID删除用户角色")
    @Override
    public ServerResponse<String> delRoleById(BaseRoleDTO baseRoleDTO) {
        if(null == baseRoleDTO || null == baseRoleDTO.getRoleId()
                || StringUtil.isEmpty(baseRoleDTO.getRoleCode())){
            return ServerResponse.createByErrorMessage("参数错误");
        }

        if(baseRoleMapper.deleteByPrimaryKey(baseRoleDTO.getRoleId()) > 0){
           //删除角色权限关联
          baseRoleMechanismMapper.deleteRoleMechanism(baseRoleDTO);

           //删除角色与用户关联
            baseUserRoleMapper.deleteUserRole(baseRoleDTO);

            return ServerResponse.createBySuccessMessage("删除成功");
        }
        return ServerResponse.createByErrorMessage("删除失败");
    }

    /**
     * 列表查询角色
     *
     * @param baseRoleDTO
     * @return
     */
    @SysLog("列表查询角色")
    @Override
    public ServerResponse<PageInfo> selectListRole(BaseRoleDTO baseRoleDTO,BaseUserVO baseUserVO) {
        if(null == baseRoleDTO ||  null ==  baseUserVO){
            return ServerResponse.createByErrorMessage("参数错误");
        }
        if(null == baseRoleDTO.getPageNum()){
            baseRoleDTO.setPageNum(Const.INITPAGENUM);
        }
        if(null == baseRoleDTO.getPageSize()){
            baseRoleDTO.setPageSize(Const.INITPAGESIZE);
        }
        PageHelper.startPage(baseRoleDTO.getPageNum(),baseRoleDTO.getPageSize(),true,false,null);
        PageHelper.orderBy(" br.id DESC");

        baseRoleDTO.setCompanyId(baseUserVO.getCompanyId());

        List<BaseRoleVO> list = baseRoleMapper.selectListRole(baseRoleDTO);
        if(null == list || 0 == list.size()){
            return ServerResponse.createByErrorMessage("没有数据");
        }
        return ServerResponse.createBySuccess("查询成功",new PageInfo(list));
    }

    /**
     * 查询角色列表
     *
     * @param baseRoleDTO
     * @return
     */
    @SysLog("查询角色列表")
    @Override
    public ServerResponse<List<BaseRoleVO>> selectAllRole(BaseRoleDTO baseRoleDTO,BaseUserVO baseUserVO) {
        if(null == baseRoleDTO ||  null ==  baseUserVO){
            return ServerResponse.createByErrorMessage("参数错误");
        }
        baseRoleDTO.setCompanyId(baseUserVO.getCompanyId());
        List<BaseRoleVO> list = baseRoleMapper.selectListRole(baseRoleDTO);
        if(null == list || 0 == list.size()){
            return ServerResponse.createByErrorMessage("没有数据");
        }
        return ServerResponse.createBySuccess("查询成功",list);
    }

    /**
     * ID查询角色信息
     *
     * @param baseRoleDTO
     * @return
     */
    @SysLog("ID查询角色信息")
    @Override
    public ServerResponse<BaseRoleVO> selectRoleById(BaseRoleDTO baseRoleDTO) {
        if(null == baseRoleDTO || null == baseRoleDTO.getRoleId()){
            return ServerResponse.createByErrorMessage("参数错误");
        }
        BaseRoleVO baseRoleVO = baseRoleMapper.selectVOById(baseRoleDTO.getRoleId());

        //查询角色组织机构数据权限ID
        List<Long> rmIdList = baseRoleMechanismMapper.getOrgIdListByRoleId(baseRoleDTO.getRoleId());

        //查询角色关联了哪些用户
        List<Long>  userIds  =  baseUserRoleMapper.getRoleListByUser(baseRoleDTO.getRoleId());

        baseRoleVO.setRmIds(rmIdList);
        baseRoleVO.setUserIds(userIds);

        if(null == baseRoleVO){
            return ServerResponse.createByErrorMessage("没有数据");
        }
        return ServerResponse.createBySuccess("查询成功",baseRoleVO);
    }

    /**
     * 启用禁用接口
     *
     * @param baseRoleDTO
     * @param baseUserVO
     * @return
     */
    @SysLog("启用禁用接口")
    @Override
    public ServerResponse<String> updateIsPublish(BaseRoleDTO baseRoleDTO, BaseUserVO baseUserVO) {
        if(null == baseRoleDTO ||  null ==  baseUserVO){
            return ServerResponse.createByErrorMessage("参数错误");
        }
         Date now = new Date();

         BaseRole baseRole =  new BaseRole();
         baseRole.setId(baseRoleDTO.getRoleId());
         baseRole.setIsPublish(baseRoleDTO.getIsPublish());
         baseRole.setUpdateTime(now);
         baseRole.setUpdateUser(baseUserVO.getUserName());
         int count =  baseRoleMapper.updateByPrimaryKeySelective(baseRole);

         if(count > 0)
         {
             return ServerResponse.createBySuccessMessage("操作成功");
         }else
         {
             return ServerResponse.createByErrorMessage("操作失败");
         }

    }

    /**
     * 设置数据权限接口
     *
     * @param baseRoleDTO
     * @param baseUserVO
     * @return
     */
    @SysLog("角色设置数据权限接口")
    @Override
    public ServerResponse<String> addRoleOrg(BaseRoleDTO baseRoleDTO, BaseUserVO baseUserVO) {
        if(null == baseRoleDTO ||  null ==  baseUserVO){
            return ServerResponse.createByErrorMessage("参数错误");
        }

        if(StringUtil.isNotEmpty(baseRoleDTO.getOrgIds())  &&  baseRoleDTO.getRoleId() != null )
        {
            //解析传的组织机构ID
            String[] split =  baseRoleDTO.getOrgIds().split(",");
            List<String> asList = Arrays.asList(split);

            baseRoleDTO.setAsList(asList);
            baseRoleDTO.setUserName(baseUserVO.getUserName());
            baseRoleDTO.setCreateOrgId(baseUserVO.getCreateOrgId());
            baseRoleDTO.setCreateTopOrgId(baseUserVO.getCreateTopOrgId());
            baseRoleDTO.setUseType(baseUserVO.getUseType());
            //批量插入角色权限
            int  count =   baseRoleMechanismMapper.addRoleOrg(baseRoleDTO);

            if(count > 0)
            {
                return ServerResponse.createBySuccessMessage("新增成功");
            }else
            {
                return ServerResponse.createByErrorMessage("新增失败");
            }

        }else
        {
            return ServerResponse.createByErrorMessage("参数错误");
        }

    }

    /**
     * 用户分配角色
     *
     * @param baseRoleDTO
     * @param baseUserVO
     * @return
     */
    @SysLog("用户分配角色")
    @Override
    public ServerResponse<String> addRoleUser(BaseRoleDTO baseRoleDTO, BaseUserVO baseUserVO) {

        if(null == baseRoleDTO ||  null ==  baseUserVO){
            return ServerResponse.createByErrorMessage("参数错误");
        }


        if(StringUtil.isEmpty(baseRoleDTO.getRoleIds())  ||  StringUtil.isEmpty(baseRoleDTO.getUserNames()) )
        {
            return ServerResponse.createByErrorMessage("参数错误");
        }



           String[] split =  baseRoleDTO.getRoleIds().split(",");

           List<String> asList = Arrays.asList(split);

            baseRoleDTO.setAsList(asList);
            baseRoleDTO.setUserName(baseUserVO.getUserName());
            baseRoleDTO.setCreateTopOrgId(baseUserVO.getCreateTopOrgId());
            baseRoleDTO.setCreateOrgId(baseUserVO.getCreateOrgId());
            baseRoleDTO.setUseType(baseUserVO.getUseType());


            int count  =  baseUserRoleMapper.addRoleUser(baseRoleDTO);


            if(count > 0)
            {
                return ServerResponse.createBySuccessMessage("新增成功");
            }else
            {
                return ServerResponse.createByErrorMessage("新增失败");
            }


    }

    /**
     * 角色关联用户
     *
     * @param baseRoleDTO
     * @param baseUserVO
     * @return
     */
    @Override
    public ServerResponse<String> addUserRole(BaseRoleDTO baseRoleDTO, BaseUserVO baseUserVO) {
        if(null == baseRoleDTO ||  null ==  baseUserVO){
            return ServerResponse.createByErrorMessage("参数错误");
        }


        if(StringUtil.isEmpty(baseRoleDTO.getRoleIds())  ||  StringUtil.isEmpty(baseRoleDTO.getUserNames()) )
        {
            return ServerResponse.createByErrorMessage("参数错误");
        }


        String[] split =  baseRoleDTO.getUserNames().split(",");

        List<String> asList = Arrays.asList(split);

        baseRoleDTO.setAsList(asList);
        baseRoleDTO.setUserName(baseUserVO.getUserName());
        baseRoleDTO.setCreateTopOrgId(baseUserVO.getCreateTopOrgId());
        baseRoleDTO.setCreateOrgId(baseUserVO.getCreateOrgId());
        baseRoleDTO.setUseType(baseUserVO.getUseType());


        int count  =  baseUserRoleMapper.addUserRole(baseRoleDTO);


        if(count > 0)
        {
            return ServerResponse.createBySuccessMessage("新增成功");
        }else
        {
            return ServerResponse.createByErrorMessage("新增失败");
        }

    }


}
